package com.hks.common.handle;

import com.hks.common.constant.StatusCode;
import com.hks.common.ex.RedisException;
import com.hks.common.ex.RequestException;
import com.hks.common.utils.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.sql.SQLException;


/**
 * 全局异常捕获处理
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler{

    //日志打印
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * redis 异常捕获处理
     * @param ex
     * @return
     */
    @ExceptionHandler(RedisException.class)
    @ResponseStatus(value = HttpStatus.NOT_IMPLEMENTED)
    public ResponseResult handleRedisException(RedisException ex){
        logger.error("redis异常：状态码：{}，异常信息：{}",ex.getCode(), ex.getMessage());
        return new ResponseResult(ex.getCode(),ex.getMessage());
    }

    /**
     * 请求异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(RequestException.class)
    @ResponseStatus(value = HttpStatus.NOT_IMPLEMENTED)
    public ResponseResult handleCustomizeException(RequestException ex){
        logger.error("请求异常：状态码：{}，异常信息：{}", ex.getCode(), ex.getMessage());
        return new ResponseResult(ex.getCode(), ex.getMessage());
    }

    /**
     * 捕获sql执行异常
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLException.class)
    @ResponseStatus(value = HttpStatus.NOT_IMPLEMENTED)
    public ResponseResult handleSQLException(SQLException ex){
        logger.error("sql执行异常：异常信息：{}", ex.getMessage());
        return new ResponseResult(StatusCode.SQL_EX, "sql执行异常："+ex.getMessage());
    }
}
